<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/5/17
  Time: 22:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="id" value="${pageContext.request.getParameter('id')}"></c:set>
<c:set var="approveFlag" value="${pageContext.request.getParameter('approveFlag')}"></c:set>
<c:set var="type" value="${pageContext.request.getParameter('type')}"></c:set>
<c:set var="repertoryId" value="${pageContext.request.getParameter('repertoryId')}"></c:set>
<title>采购 - 退货订单详情</title>

<%--<link rel="stylesheet" href="${contextPath}/static/layer/css/layui.css" media="all">--%>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jquery-ui/jquery-ui.css"/>
<%--<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">--%>
<link rel="stylesheet"
      href="${contextPath}/static/ace/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jqgrid/ui.jqgrid.css"/>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<%--<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>--%>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<%--<jsp:include page="../../../head.jsp"/>--%>
<style type="text/css">
    .customBtn {
        line-height: 20px;
        margin-bottom: 3px;
    }

    .btnLine {
        margin-left: 1px;
        margin-top: 8px;
        margin-bottom: 2px;
    }

    @-webkit-keyframes bouncedelay {
        0%, 80%, 100% {
            -webkit-transform: scale(0.0)
        }
        40% {
            -webkit-transform: scale(1.0)
        }
    }

    @keyframes bouncedelay {
        0%, 80%, 100% {
            transform: scale(0.0);
            -webkit-transform: scale(0.0);
        }
        40% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
    }

    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }

    .ui-jqgrid-sortable {
        text-align: center;
    }
</style>

<div class="row" id="app">
    <div class="row btnLine">
        <div class="button-len col-sm-12">
            <div style="width: 100%; margin-bottom: 10px;">
                <%--<a href="${contextPath}/sys/user/home#page/franchiseePrementDocumentsOrdergds">--%>
                    <button class="btn btn-white btn-sm btn-purple customBtn" id="" onclick="javascript:window.history.go(-1);window.close();">
                        <i class="ace-icon fa fa-plus-circle purple"></i> 返回
                    </button>
                <%--</a>--%>
                <shiro:hasPermission name="SALESRETURN:START:ADD">
                    <button class="btn btn-white btn-info btn-sm customBtn" id="fqthuo">
                        <i class="ace-icon fa fa-pencil blue"></i> 发起退货
                    </button>
                    <label style="">退货类型：</label>
                    <select class="input-sm" id="exType">
                        <c:if test="${repertoryId != '0'}">
                            <option value="0">==请选择==</option>
                            <option value="1">仓配退货单</option>
                            <option value="3">直配退货单</option>
                        </c:if>
                        <c:if test="${repertoryId == '0'}">
                            <option value="2">统采退货单</option>
                        </c:if>
                    </select>
                </shiro:hasPermission>

                <label id="depotLabel" class="hide" style="">类型：</label>
                <select class="input-sm hide" id="depotType">
                    <option value="-1">==请选择==</option>
                    <option :value="obj.depotId" :name="obj.depotName" v-for="(obj, index) in depotObj">{{ obj.depotName }}</option>
                </select>
            </div>
        </div>
    </div>

    <div class="col-xs-12">

        <table id="grid-table"></table>

        <div id="grid-pager"></div>

    </div>
    <!-- 内容数据结束 -->

    <!-- 模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="">
            <div class="modal-content">
                <div class="modal-header" style="font-size: 20px; margin-bottom: -15px;">
                    <h4 class="modal-title" id="myModalLabel">
                        要货订单 - <span id="alertTitle">商品新增</span>
                        <small id="smallTitle" class="hide" style="color: red; float: right; margin-top: 10px;"></small>

                    </h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <table class="table">
                            <tbody>
                            <tr>
                                <th>
                                    <div class="row btnLine">
                                        <div class="button-len col-sm-12">
                                            <label for="" style="margin-left: 8px;">商品类型：</label>
                                            <select class="input-sm" id="isExpInput">
                                                <option value="0">商品类型</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType1">
                                                    {{ obj.typeName }}
                                                </option>

                                            </select>
                                            <select class="input-sm" id="isAuthInput">
                                                <option value="-1">商品大类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType2">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>

                                            <select class="input-sm" id="isAuthInput1">
                                                <option value="-1">商品中类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType3">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>

                                            <select class="input-sm" id="isAuthInput2">
                                                <option value="-1">商品小类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType4">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>
                                        </div>
                                    </div>
                                </th>
                            </tr>
                            <tr>
                                <th>
                                    <input class="input-sm" type="text" id="productCode" style="margin-left: 20px;"
                                           placeholder="商品条码">
                                    <input class="input-sm" type="text" id="productName" style="margin-left: 5px;"
                                           placeholder="商品名称">
                                    <button class="btn btn-sm btn-white btn-info search-len customBtn"
                                            v-on:click="">
                                        <i class="ace-icon fa fa-search orange"></i>搜索
                                    </button>
                                </th>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 内容数据开始 -->
                    <div class="button-len col-sm-12" style="margin-bottom: 10px;">
                        <table id="grid-shop-table"></table>
                        <div id="grid-shop-pager"></div>
                    </div>
                    <!-- 内容数据结束 -->
                    <div style="text-align: right;">
                        <button class="btn btn-white btn-info btn-sm customBtn btn-xs" type="button"
                                onclick="submitCtyShop()">添加
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default btn-xs" data-dismiss="modal" v-on:click="close">关闭
                    </button>
                    <%--<button type="button" class="btn btn-primary btn-xs" v-on:click="saveSupplier">提交更改</button>--%>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>


    <!-- 模态框（Modal） -->
    <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="">
            <div class="modal-content">
                <div class="modal-header" style="font-size: 20px; margin-bottom: -15px;">
                    <h4 class="modal-title" id="myModalLabel1">
                        退货 - <span id="alertTitle1"></span>
                        <small id="smallTitle1" class="hide"
                               style="color: red; float: right; margin-top: 10px;"></small>

                    </h4>
                </div>
                <div class="modal-body">
                    <div id="gys" class="hide">
                        <label style="margin-left: 26px">供应商：</label>
                        <select class="input-sm" id="supplierId">
                            <option :value="obj.supplierName" :name="obj.supplierId" v-for="obj in objcte">{{
                                obj.supplierName }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <%--<button type="button" class="btn btn-default btn-xs" data-dismiss="modal" v-on:click="close">关闭</button>--%>
                    <button type="button" class="btn btn-primary btn-xs" id="supp">保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</div>
</div>

<!-- page specific plugin scripts -->
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<script src=${contextPath}/static/layer/layui.all.js></script>
<!-- 公用属性 -->
<script type="text/javascript">
    var approveFlag = '${approveFlag}';
    var lastsel;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";


    var grid_shop_selector = "#grid-shop-table";
    var pager_shop_selector = "#grid-shop-pager";

    //获取选择数据的Id，（获取单条数据id 使用selrow，获取多条数据Id 使用selarrrow）
    //    var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
    //获取选择数据的的整条数据（数据类型 集合）
    //    var rowData = $(grid_selector).jqGrid('getRowData', id);
    //获取选择数据的Id，（数组类型）
    //    var ids = $(grid_shop_selector).jqGrid('getGridParam', 'selarrrow');

    var requireShopName_id = '';

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    var queryModel = {
        //分页参数
        page: '1',
        rows: '10',
    }

    var app = new Vue({
        el: '#app',
        data: {
            objcte: [],
            depotObj: [],   //仓库集合
            //商品类型下拉
            yanType1: [],
            yanType2: [],
            yanType3: [],
            yanType4: [],
            yanType5: [],
        },
        methods: {
//            addProduct: function () {
//                shopInfo();
//                $('#myModal').modal('show');
//            }
        }
    })

    $("#addCargo").click(function () {
        shopInfo();
    });
    

</script>

<script type="text/javascript" src="${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="${contextPath}/static/layer/layer.js"></script>
<!-- 退货订单商品列表加载 -->
<script type="text/javascript">
    var scripts = [null, "${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js", "${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js", "${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js", "${contextPath}/static/layer/layer.js", null]
    $('.page-content-area').ace_ajax('loadScripts', scripts, function () {
        jQuery(function ($) {
            var parent_column = $(grid_selector).closest('[class*="col-"]');
            //resize to fit page size
            $(window).on('resize.jqGrid', function () {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            })

            //resize on sidebar collapse/expand
            $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                    //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                    setTimeout(function () {
                        $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                    }, 20);
                }
            })

            jQuery(grid_selector).jqGrid({
                //direction: "rtl",
                //subgrid options
                subGrid: false,
                url: "${contextPath}/ktPurchase/getPurchaseItems?id=${id}",
                //data: grid_data,
                datatype: "json",
                mtype: 'POST',
                height: 300,
                colNames: ['id', '商品名称', '商品编码', '单位', '规格', '单价', '数量', '实际数量', '金额', '状态', 'supplierId', '接收方', '退货方id', '退货方', 'type', '处理状态', 'purchaseOrderItemId', 'purchaseId'],
                colModel: [
                    {name: 'id', index: 'id', editable: false, hidden: true},
                    {name: 'productName', index: 'productName', editable: false},
                    {
                        name: 'productCode',
                        index: 'productCode',
                        editable: false,
                        sortable: false,
                        editrules: {required: true}
                    },
                    {name: 'unit', index: 'unit', editable: false, sortable: false,},
                    {
                        name: 'spec',
                        index: 'spec',
                        editable: false,
//                        align: 'right',
                        sortable: false
                    },
                    {
                        name: 'cstPrice',
                        index: 'cstPrice',
                        align: 'right',
                        editable: false,
                        sortable: false,
                        editrules: {required: true}
                    },
                    {
                        name: 'quantity', index: 'quantity', editable: true, sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            var id = rowObject.productCode;
                            var cstPrice = rowObject.cstPrice;
                            var quantity = rowObject.quantity;
                            if (!quantity) {
                                quantity = "0"
                            }
                            return ' <input type="text" id="realQuantity_' + id + '" value="' + quantity + '" onblur="discount(' + id + ',' + cstPrice + ')" style="background-color: #ffffff; border:0;outline:0; margin-top: -16px;float: right; text-align: right" />';
                        }
                    },
                    {
                        name: 'realQuantity', index: 'realQuantity', editable: true, sortable: false, align: 'right',
//                        formatter: function (cellvalue, options, rowObject) {
//                            var id = rowObject.productCode;
//                            var cstPrice = rowObject.cstPrice;
//                            var quantity = rowObject.quantity;
//                            if (!quantity) {
//                                quantity = "0"
//                            }
//                            return ' <input type="text" id="realQuantity_' + id + '" value="' + quantity + '" onblur="discount(' + id + ',' + cstPrice + ')" style="background-color: #ffffff; border:0;outline:0; margin-top: -16px;float: right; text-align: right" />';
//                        }
                    },

                    {
                        name: 'amt',
                        index: 'amt',
                        editable: false,
                        sortable: false,
                        align: 'right',
                        formatter: function (cellvalue, options, rowObject) {
                            var id = rowObject.productCode;
                            var cstPrice = rowObject.cstPrice;
                            var quantity = rowObject.quantity;
                            var price = (cstPrice * quantity).toFixed(2);
                            return ' <div id="price_' + id + '"  style="margin-top: 1px;float: right;">' + price + '</div>';
                        }
                    },
                    {
                        name: 'approveFlag',
                        index: 'approveFlag',
                        editable: false,
                        sortable: false,
                        hidden: true,
                        formatter: function (v, x, r) {
                            var type = r.type;
                            if (type == '3') {
                                return '已发起';
                            }
                            if (type == '1') {
                                return '退货完成';
                            }
                            return '待处理';
                        },
                    },
                    {
                        name: 'supplierId',
                        index: 'supplierId',
                        editable: false,
                        hidden: true,
                        sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            if (!cellvalue){
                                cellvalue = '0';
                            }
                            return cellvalue;
                        }
                    },
                    {
                        name: 'supplierName',
                        index: 'supplierName',
                        editable: false,
//                        hidden:true,
                        sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            var productCode = rowObject.productCode;
                            var supplierName = rowObject.supplierName;
                            if (!supplierName) {
                                supplierName = '默认供应商';
                            }
                            return '<div id="supplierName_' + rowObject.productCode + '" onclick="ckRequireShopId('+productCode+')">' + supplierName + '</div>';
                        }
                    },
                    {
                        name: 'shopId',
                        index: 'shopId',
                        editable: false,
                        sortable: false,
                        hidden: true,
//                        formatter: function (cellvalue, options, rowObject) {
//                            var shopId = rowObject.shopId;
//                            if (!shopId) {
//                                shopId = '';
//                            }
//                            return '<div  id="shopId_' + rowObject.productCode + '">' + shopId + '</div>';
//                        }
                    },
                    {
                        name: 'shopName',
                        index: 'shopName',
                        editable: false,
                        sortable: false,
//                        hidden:true,
//                        formatter: function (cellvalue, options, rowObject) {
//                            var shopName = rowObject.shopName;
//                            if (!shopName) {
//                                shopName = '';
//                            }
//                            return '<div  id="shopName_' + rowObject.productCode + '">' + shopName + '</div>';
//                        }
                    },
                    {
                        name: 'type',
                        index: 'type',
                        editable: false,
                        sortable: false,
                        hidden:true,
                    },
                    {
                        name: 'typeName',
                        index: 'typeName',
                        editable: false,
                        sortable: false,
//                        hidden:true,
                        formatter: function (cellvalue, options, rowObject) {
                            var type = rowObject.type;
                            if (type == '5') {
                                return '待处理'
                            }
                            if (type == '8'){
                                return '仓配退货已完成'
                            }
                            if (type == '10'){
                                return '统采退货已完成'
                            }
                            if (type == '9'){
                                return '直配退货已完成'
                            }
                            return '-'

                        }
                    },
                    {
                        name: 'purchaseOrderItemId',
                        index: 'purchaseOrderItemId',
                        editable: false,
                        sortable: false,
                        hidden:true,
                    },
                    {
                        name: 'purchaseId',
                        index: 'purchaseId',
                        editable: false,
                        sortable: false,
                        hidden:true,
                    },
                ],
                //                rownumbers: true, //自动行数
//                height:"100%",   //高度自适应
//			width: "100%",
                autowidth: true,  //宽度自适应
                viewrecords: true,
                rowNum: 1000,
                rowList: [10, 20, 30],
//                pager: pager_selector,
                altRows: true,
                //toppager: true,

                multiselect: true,
                //multikey: "ctrlKey",
                multiboxonly: true,

                loadComplete: function () {
                    var table = this;
                    setTimeout(function () {
                        styleCheckbox(table);

                        updateActionIcons(table);
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },

                editurl: "${contextPath}/ktProd/getProdInfo",//nothing is saved
                caption: "商品列表",
                jsonReader: {
                    root: "recordList",
                    page: "currentPage",
                    total: "pageCount",
                    records: "recordCount"
                },
//                onSelectAll: function(rowids,statue){
//                    //函数里做自己的处理
//					queryModel.rowIds = rowids;
//                },
//                resetSelection: function(rowid){
//
//                    return(rowid)
//				}
                //双击
//                ondblClickRow: function () {
//                    var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
//                    var rowData = $(grid_selector).jqGrid('getRowData', id);
//                    $("#thlx").addClass("hide");
//                    $("#gys").removeClass("hide");
////                    console.log(双击);
//                    pageInit(rowData.productCode)
//                    $('#myModal1').modal('show');
//                },
                //点击
//                onSelectRow : function(id) {
//                    if (id && id !== lastsel) {
//                        jQuery(grid_selector).jqGrid('restoreRow', lastsel);
//                        jQuery(grid_selector).jqGrid('editRow', id, true);
//                        lastsel = id;
//                    }
//                },
//                editurl : ctx+"/RowEditing",
//                caption : "Using events example"
            });
            jQuery(grid_selector).jqGrid('navGrid', grid_selector, {
                edit : false,
                add : false,
                del : false
            });
                //,autowidth: true,


                /**
                 ,
                 grouping:true,
                 groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
                 caption: "Grouping"
                 */

//            });

            function cLink(cellvalue, options, rowObject) {
                var id = rowObject.id;
                return '<a href="${contextPath}/sys/user/home#page/prementDocumentsTakedelivery" onclick="">', id, '</a>';
            }

            $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

            $("#editShop").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    layer.msg("提示：请选择一条信息");
                    return;
                }
                $(grid_selector).jqGrid("editGridRow", id, {
                    // edit record form
                    width: 500,
                    closeAfterEdit: true,
                    //editData :
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />');
                        style_edit_form(form);
                    },
                    afterShowForm: function (e) {
                        var form = $(e[0]);
                        //console.log(form)

                        $.ajax({
                            url: '${contextPath}/ktPurchase/saveSupplier',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#quXianName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' , suggestion.value , ', ' , suggestion.data);
                                            //selectChannelNameToSelected(suggestion.value)
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectEmpNameToSelected?channelName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#empName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            ////console.log('You selected: ' , suggestion.value , ', ' , suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectChannelNameToSelected?quXianName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#realChannelName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' , suggestion.value , ', ' , suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectMaterialCompanyToSelected',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#materialCompany').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' , suggestion.value , ', ' , suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        })

                    },
                    afterSubmit: function (response, postdata) {
                        var result = eval('(', response.responseText, ')');
                        ////console.log(result);
                        return [result.success, result.message, 0];
                    },
                    errorTextFormat: function (response) {
                        ////console.log("错误",response.responseText);
                        //var result = response.responseText;
                        return "服务器异常，稍后再试";
                    }
                });
            });


            $("#initializeUserPassword").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    $.jgrid.info_dialog("提示：", "请选择一条用户信息");
                    return;
                }
                //询问框
                layer.confirm('将会把用户密码初始化为用户的手机号码', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    var rowData = $(grid_selector).jqGrid('getRowData', id);
                    //layer.load(1);
                    $.ajax({
                        url: '${contextPath}/sys/user/initializeUserPassword?phone=' + rowData.phone,
                        // async : false,
                        success: function (data) {
                            layer.closeAll('loading');
                            if (data.success) {
                                layer.msg('初始化成功', {icon: 1});

                            } else {
                                layer.msg(data.message);
                            }

                        },
                        error: function (error) {
                            layer.closeAll('loading');
                            $.jgrid.info_dialog("提示：", "服务器异常，稍后再试");
                        }

                    })

                }, function () {

                });
            })
            //enable search/filter toolbar
            //jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
            //jQuery(grid_selector).filterToolbar({});


            //switch element when editing inline
            function aceSwitch(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=checkbox]')
                        .addClass('ace ace-switch ace-switch-5')
                        .after('<span class="lbl"></span>');
                }, 0);
            }

            //enable datepicker
            function pickDate(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=text]')
                        .datepicker({format: 'yyyy-mm-dd', autoclose: true});
                }, 0);
            }


            //navButtons
            jQuery(grid_selector).jqGrid('navGrid', pager_selector,
                { 	//navbar options
                    edit: false,
                    editicon: 'ace-icon fa fa-pencil blue',
                    add: false,
                    addicon: 'ace-icon fa fa-plus-circle purple',
                    del: false,
                    delicon: 'ace-icon fa fa-trash-o red',
                    search: false,
                    searchicon: 'ace-icon fa fa-search orange',
                    refresh: true,
                    refreshicon: 'ace-icon fa fa-refresh green',
                    view: false,
                    viewicon: 'ace-icon fa fa-search-plus grey',
                },
                {
                    //edit record form
                    //closeAfterEdit: true,
                    //width: 700,
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //new record form
                    //width: 700,
                    closeAfterAdd: true,
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //delete record form
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        if (form.data('styled')) return false;

                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_delete_form(form);

                        form.data('styled', true);
                    },
                    onClick: function (e) {
                        //alert(1);
                    }
                },
                {
                    //search form
                    recreateForm: true,
                    afterShowSearch: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                        style_search_form(form);
                    },
                    afterRedraw: function () {
                        style_search_filters($(this));
                    }
                    ,
                    multipleSearch: true,
                    /**
                     multipleGroup:true,
                     showQuery: true
                     */
                },
                {
                    //view record form
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    }
                }
            )


            function style_edit_form(form) {
                //enable datepicker on "sdate" field and switches for "stock" field
                //form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})

                //form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
                //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
                //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');


                //update buttons classes
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
                buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
                buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

                buttons = form.next().find('.navButton a');
                buttons.find('.ui-icon').hide();
                buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
                buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
            }

            function style_delete_form(form) {
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
                buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
                buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
            }

            function style_search_filters(form) {
                form.find('.delete-rule').val('X');
                form.find('.add-rule').addClass('btn btn-xs btn-primary');
                form.find('.add-group').addClass('btn btn-xs btn-success');
                form.find('.delete-group').addClass('btn btn-xs btn-danger');
            }

            function style_search_form(form) {
                var dialog = form.closest('.ui-jqdialog');
                var buttons = dialog.find('.EditTable')
                buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
                buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
                buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
            }

            function beforeDeleteCallback(e) {
                var form = $(e[0]);
                if (form.data('styled')) return false;

                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_delete_form(form);
                form.data('styled', true);
            }

            function beforeEditCallback(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_edit_form(form);
            }


            //it causes some flicker when reloading or navigating grid
            //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
            //or go back to default browser checkbox styles for the grid
            function styleCheckbox(table) {
                /**
                 $(table).find('input:checkbox').addClass('ace')
                 .wrap('<label />')
                 .after('<span class="lbl align-top" />')


                 $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
                 .find('input.cbox[type=checkbox]').addClass('ace')
                 .wrap('<label />').after('<span class="lbl align-top" />');
                 */
            }


            //unlike navButtons icons, action icons in rows seem to be hard-coded
            //you can change them like this in here if you want
            function updateActionIcons(table) {
                /**
                 var replacement =
                 {
                     'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                     'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                     'ui-icon-disk' : 'ace-icon fa fa-check green',
                     'ui-icon-cancel' : 'ace-icon fa fa-times red'
                 };
                 $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon ',replacement[$class]);
			})
                 */
            }

            //replace icons with FontAwesome icons like above
            function updatePagerIcons(table) {
                var replacement =
                    {
                        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                    };
                $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                    var icon = $(this);
                    var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                    if ($class in replacement) icon.attr('class', 'ui-icon ', replacement[$class]);
                })
            }

            function enableTooltips(table) {
                $('.navtable .ui-pg-button').tooltip({container: 'body'});
                $(table).find('.ui-pg-div').tooltip({container: 'body'});
            }

            //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

            $(document).one('ajaxloadstart.page', function (e) {
                $.jgrid.gridDestroy(grid_selector);
                $('.ui-jqdialog').remove();
            });
        });
    });
</script>
<!-- 商品列表详情 -->
<script>
    function shopInfo() {
        $('#myModal').modal('show');
        jQuery(grid_shop_selector).jqGrid({
            subGrid: false,
            url: '${contextPath}/ktProd/getProdInfo',
            datatype: "json",
            mtype: 'POST',
            height: 300,
            colNames: ['ID', '商品名称', '供应名称', '类型', '条码', '状态', '单位', '规格', '操作时间'],
            colModel: [
                {name: 'productId', index: 'productId', width: 30, editable: true},
                {
                    name: 'productName',
                    index: 'productName',
                    width: 90,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },
//                    {name: 'supplierId', index: 'productId', width: 60, editable: true},
                {
                    name: 'supplierName', index: 'productId', width: 78, editable: true,
                    edittype: 'select'
                },
                {
                    name: 'prodTypeName',
                    index: 'prodTypeName',
                    width: 60,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },
                {
                    name: 'productCode',
                    index: 'productCode',
                    width: 60,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },

                {
                    name: 'state',
                    index: 'state',
                    width: 40,
                    editable: true,
                    sortable: false,
                    edittype: 'select',
                    formatter: function (v, x, r) {
                        return r['state'] == "1" ? "有效" : "无效";
                    },
                    editoptions: {value: "0:有效;1:无效"}
                },
                {
                    name: 'unit',
                    index: 'unit',
                    width: 30,
                    editable: true,
                    sortable: false
                }, {
                    name: 'spec',
                    index: 'spec',
                    width: 60,
                    editable: true,
                    sortable: false
                },
                {name: 'stateDate', index: 'stateDate', width: 60, editable: false}

            ],
//                rownumbers: true, //自动行数
            height: "100%",   //高度自适应
//			width: "100%",
            autowidth: true,  //宽度自适应
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pager_shop_selector,
            altRows: true,
            //toppager: true,

            multiselect: true,
            //multikey: "ctrlKey",
            multiboxonly: true,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    styleCheckbox(table);

                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },

            editurl: "${contextPath}/ktProd/getShopListByPage",//nothing is saved
            caption: "店铺列表",
            jsonReader: {
                root: "recordList",
                page: "currentPage",
                total: "pageCount",
                records: "recordCount"
            },
//                onSelectAll: function(rowids,statue){
//                    //函数里做自己的处理
//					queryModel.rowIds = rowids;
//                },
//                resetSelection: function(rowid){
//
//                    return(rowid)
//				}

            //,autowidth: true,


            /**
             ,
             grouping:true,
             groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
             caption: "Grouping"
             */

        });
        //it causes some flicker when reloading or navigating grid
        //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
        //or go back to default browser checkbox styles for the grid
        function styleCheckbox(table) {
            /**
             $(table).find('input:checkbox').addClass('ace')
             .wrap('<label />')
             .after('<span class="lbl align-top" />')


             $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
             .find('input.cbox[type=checkbox]').addClass('ace')
             .wrap('<label />').after('<span class="lbl align-top" />');
             */
        }


        //unlike navButtons icons, action icons in rows seem to be hard-coded
        //you can change them like this in here if you want
        function updateActionIcons(table) {
            /**
             var replacement =
             {
                 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                 'ui-icon-disk' : 'ace-icon fa fa-check green',
                 'ui-icon-cancel' : 'ace-icon fa fa-times red'
             };
             $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
             */
        }

        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                    'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container: 'body'});
            $(table).find('.ui-pg-div').tooltip({container: 'body'});
        }

        //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

    }
</script>
<!-- 商品下拉菜单 -->
<script>
    /**
     * 下啦联动数据绑定 开始代码
     * @type {{parentId: string}}
     */
    $('#isExpInput').change(function () {
        app.yanType2 = []
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isExpInput option:selected").val();
        querySubProdType2()
    });

    $('#isAuthInput').change(function () {
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput option:selected").val();
        querySubProdType3()
    });

    $('#isAuthInput1').change(function () {
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput1 option:selected").val();
        querySubProdType4()
    });

    $('#isAuthInput2').change(function () {
        app.yanType5 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = "";
        queryModel.typeId = $("#isAuthInput2 option:selected").val();
        querySubProdType5()
    });

    var querySubProdType1 = function () {
        getSubProdType1(queryModel)
    }
    var querySubProdType2 = function () {
        getSubProdType2(queryModel)
    }
    var querySubProdType3 = function () {
        getSubProdType3(queryModel)
    }
    var querySubProdType4 = function () {
        getSubProdType4(queryModel)
    }
    var querySubProdType5 = function () {
        getSubProdType5(queryModel)
    }


    var getSubProdType1 = function (queryModel) {
        // console.log(queryModel)

//        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0) {
                    layer.msg("查询没有数据")
                    return
                }
//                 console.log("dataArray: "+dataArray)
                app.yanType1 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType2 = function (queryModel) {
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0) {
                    layer.msg("查询没有数据")
                    return
                }
                console.log("dataArray: " + dataArray)
                app.yanType2 = dataArray;

            },
            error: function (error) {
            }
        })
    }

    var getSubProdType3 = function (queryModel) {
//        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0) {
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType3 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType4 = function (queryModel) {
        // console.log(queryModel)
//        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0) {
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType4 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType5 = function (queryModel) {
        // console.log(queryModel)
//        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getProdProperty',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0) {
                    layer.msg("查询没有数据")
                    return
                }
                $("#commodityScreen").removeClass("hide");
                console.log("dataArray: " + dataArray)
                app.yanType5 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    querySubProdType1(queryModel);

    /**
     * 下啦联动数据绑定 结束代码
     */
</script>
<!-- 业务处理 -->
<script>

    /*** 根据不同的退货类型获取退货方开始 ***/
    var getDepot = function () {
        $.ajax({
            url: '${contextPath}/ktPurchase/getPurchaseItems&id=1',   //更换获取仓库接口
            type: 'post',
            async: false,
//            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false) {
//                    layer.msg("获取出错：" + data.message)
                    return
                }
//                var dataArray = data;

                app.depotObj = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }
    var exTypeChange = function () {
        var exType = $("#exType").val();
        if (exType == '1') {
            getDepot();
            var dataArray = [
                {depotId: '0', depotName: '总部'},
            ]
            app.depotObj = dataArray;

            $("#depotLabel").removeClass('hide');
            $("#depotType").removeClass('hide');
        }else {
            $("#depotLabel").addClass('hide');
            $("#depotType").addClass('hide');
        }
    }
    exTypeChange()
    $("#exType").change(function () {
        exTypeChange();
    })
    /**************************************/

    /************ 根据不同的仓库更换jqgrid 数据 *************/
    $("#depotType").change(function () {
        var exType = $("#exType").val();
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        if(ids.length == 0){
            $("#depotType").val('-1');
            layer.msg("提示：请先选择商品！")
            return
        }
        var supplierId = $("#depotType").val();
        var supplierName = $("#depotType").find('option:selected').attr('name');
        for (var i=0;i<ids.length;i++){
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var supplierName_id = "#supplierName_" + rowData.productCode;
            if(exType != '2') {
                $(supplierName_id).html(supplierName);
                $(grid_selector).jqGrid('setCell', ids[i], "supplierId", supplierId);  //修改行数据
            }else {
                $(grid_selector).jqGrid('setCell', ids[i], "shopId", supplierId);  //修改行数据
                $(grid_selector).jqGrid('setCell', ids[i], "shopName", supplierName);  //修改行数据
            }
        }
    });
    /*****************************************************/

    //jqgrid 列事件
    var ckRequireShopId = function (productCode) {
        $("#thlx").addClass("hide");
        $("#gys").removeClass("hide");
        pageInit(productCode)
        $('#myModal1').modal('show');
    }

    //提交商品列表生成货订单
    var submitReq = function () {
//        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) {
            layer.msg("提示：你没有选择添加商品！");
            return;
        }
        var prodList = [];
        for (var i = 0; i < ids.length; i++) {
            var idArray = {};
            idArray.id = ids[i];
            prodList.push(idArray);
        }
        prodList.id = idArray;
//        console.log(JSON.stringify(prodList));
        queryModel.prodList = JSON.stringify(prodList);
//        queryModel.id = id;

        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktPurchase/saveShopRequireOrder',
            type: 'post',
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                layer.closeAll('loading')
//                reload()     //刷新列表
            },
            error: function (error) {
                layer.closeAll('loading')
                layer.msg("提示：" + error.message)
            }
        })
    }

    /*************   发起退货 **************/
    var quantityId = ''
    var approveFlag = '${approveFlag}'

    queryModel.batchNo = '${id}';
    $("#fqthuo").click(function () {
        //layer.load(1);
        var type = '${type}'
        var exType = $("#exType").val();
        if(approveFlag == '1'){
            layer.closeAll('loading');
            layer.msg("提示：订单已处理")
            return
        }
        if(exType == '0'){
            layer.closeAll('loading');
            layer.msg("提示：请选择退货类型")
            return
        }
        if (type != '') {
            if (exType == "1") {
                notProdList(exType)
            }
            if (exType == "2") {
                notProdList1(exType)
            }
            if (exType == "3") {
                notProdList2(exType)
            }
        }
        layer.closeAll('loading');
    })

    var notProdList = function (exType) {
//        //layer.load(1);
        var depotType = $("#depotType").val();
        if (depotType == '-1'){
            layer.closeAll('loading');
            layer.msg("提示：请选择仓库");
            return;
        }

        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        if(ids.length == 0){
            layer.closeAll('loading');
            layer.msg("提示：请选择商品！")
            return
        }
        var prodList = [];
        var requireShopId = '0';
        var supplierId = '';
        for (var i = 0; i < ids.length; i++) {
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            if(rowData.type == '8'){
                layer.closeAll('loading');
                layer.msg("提示：商品已发起！")
                return
            }

            if(!rowData.shopName){
                layer.closeAll('loading');
                layer.msg("提示：请选择供应商！");
                return;
            }

            requireShopId = rowData.supplierId;
            if (i == 0){
                supplierId = requireShopId;
            }

            if(exType == '2'){
                if(!rowData.supplierId){
                    layer.closeAll('loading');
                    layer.msg("提示：直配退货供应商不能为空！")
                    return
                }
            }

            if(supplierId != requireShopId){
                layer.closeAll('loading');
                layer.msg("提示：接收方不一致，不能发起！")
                return
            }


            quantityId = "#realQuantity_" + rowData.productCode;
            var idArray = {};
            idArray.productCode = rowData.productCode;

            var quantity = $(quantityId).val();
            if(exType == '1'){
                requireShopId = '0';
            }
            queryModel.shopId = requireShopId;
            idArray.shopId = requireShopId;
            idArray.type = '8';
            idArray.requireShopId = rowData.shopId;
            queryModel.requireShopId = rowData.shopId;
            idArray.quantity = quantity;
            idArray.purchaseOrderItemId = rowData.purchaseOrderItemId;
            idArray.purchaseId = rowData.purchaseId;
            prodList.push(idArray);

        }
        prodList.id = idArray;
        queryModel.prodList = JSON.stringify(prodList);
        queryModel.requireId = '${id}';
        queryModel.type = '8';
        queryModel.approveFlag = '3';
//        console.log(queryModel)
        //layer.load(1);
        $.ajax({
            url: '${contextPath}/ktPurchase/createInOutStockOrder',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                $("#depotType").val('-1');
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
//        queryModel.approveFlag = '1';
        queryModel.id = '${id}'
        /*******
        $.ajax({
            url: '${contextPath}/ktPurchase/purchaseOrderCheck',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                approveFlag = '1';
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
         *******/
    }

    var notProdList1 = function (exType) {
//        //layer.load(1);
//        var depotType = $("#depotType").val();
//        if (depotType == '-1'){
//            layer.closeAll('loading');
//            layer.msg("提示：请选择仓库");
//            return;
//        }
//        var ids = $(grid_selector).getDataIDs(); //获取表格全部数据
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');

        if(ids.length == 0){
            layer.closeAll('loading');
            layer.msg("提示：请选择商品！")
            return
        }
//        console.log(ids)
        var prodList = [];
        var supplierId = '';
        for (var i = 0; i < ids.length; i++) {
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
//            console.log(rowData)
//            if(rowData.shopId != '0'){
//                layer.msg("提示：只有总部才可以发起统采退货");
//                return;
//            }
            if(rowData.type == '10'){
                layer.closeAll('loading');
                layer.msg("提示：商品已发起！")
                return
            }

            if(!rowData.supplierId){
                layer.closeAll('loading');
                layer.msg("提示：直配退货供应商不能为空！")
                return
            }

            var requireShopId = rowData.supplierId;

            if (i == 0){
                supplierId = requireShopId;
            }

//            console.log(supplierId)
//            console.log(requireShopId)
            if(supplierId != requireShopId){
                layer.closeAll('loading');
                layer.msg("提示：接收方不一致，不能发起！")
                return
            }


            quantityId = "#realQuantity_" + rowData.productCode;
            var idArray = {};
            idArray.productCode = rowData.productCode;

            var quantity = $(quantityId).val();

            queryModel.shopId = rowData.shopId;
            idArray.shopId = rowData.shopId;

            idArray.requireShopId = requireShopId;
            queryModel.requireShopId = requireShopId;
            idArray.type = '10';
            idArray.quantity = quantity;
            idArray.purchaseOrderItemId = rowData.purchaseOrderItemId;
            idArray.purchaseId = rowData.purchaseId;
            prodList.push(idArray);

        }
        prodList.id = idArray;
        queryModel.prodList = JSON.stringify(prodList);
        queryModel.requireId = '${id}';
        queryModel.type = '10';
        queryModel.approveFlag = '3';
//        console.log(queryModel)
        //layer.load(1);
        $.ajax({
            url: '${contextPath}/ktPurchase/saveShopOutstockOrder',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                if (data.success == false) {
                    layer.closeAll('loading');
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                $("#depotType").val('-1');
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
        queryModel.id = '${id}'
//        queryModel.approveFlag = '1';
        /**********
        $.ajax({
            url: '${contextPath}/ktPurchase/purchaseOrderCheck',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                approveFlag = '1';
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
         ***********/
    }

    var notProdList2 = function (exType) {
//        //layer.load(1);
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        if(ids.length == 0){
            layer.closeAll('loading');
            layer.msg("提示：请选择商品！")
            return
        }
        var prodList = [];
        var supplierId = '';
        for (var i = 0; i < ids.length; i++) {
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            console.log(rowData)
            if(rowData.type == '9'){
                layer.closeAll('loading');
                layer.msg("提示：商品已发起完成！")
                return
            }

            console.log(rowData);
            if(!rowData.supplierId){
                layer.closeAll('loading');
                layer.msg("提示：请选择供应商！");
                return;
            }

            var requireShopId = rowData.supplierId;

            if(exType == '3'){
                if(!rowData.supplierId){
                    layer.closeAll('loading');
                    layer.msg("提示：直配退货供应商不能为空！")
                    return
                }
            }

            if (i == 0){
                supplierId = requireShopId;
            }

            if(supplierId != requireShopId){
                layer.closeAll('loading');
                layer.msg("提示：接收方不一致，不能发起！")
                return
            }

            quantityId = "#realQuantity_" + rowData.productCode;
            var idArray = {};
            idArray.productCode = rowData.productCode;

            var quantity = $(quantityId).val();

            queryModel.shopId = rowData.shopId;
            idArray.shopId = rowData.shopId;
            idArray.type = '9';
            idArray.requireShopId = requireShopId;
            queryModel.requireShopId = requireShopId;
            idArray.quantity = quantity;
            idArray.purchaseOrderItemId = rowData.purchaseOrderItemId;
            idArray.purchaseId = rowData.purchaseId;
            prodList.push(idArray);
        }
        prodList.id = idArray;
        queryModel.prodList = JSON.stringify(prodList);
        queryModel.requireId = '${id}';
        queryModel.type = '9';
        queryModel.approveFlag = '3';
        console.log(queryModel)

//        return;
        //layer.load(1)
        $.ajax({
            url: '${contextPath}/ktPurchase/saveShopOutstockOrder',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                $("#depotType").val('-1');
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
        queryModel.id = '${id}'
//        queryModel.approveFlag = '1';
        /***
        $.ajax({
            url: '${contextPath}/ktPurchase/purchaseOrderCheck',
            type: 'post',
            async: false,
            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示：" + data.message)
                ////approveFlag = '1';
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
                layer.msg("提示：服务器异常")
            }
        })
         ***/
    }
    /************************************/

    var pageInit = function (productCode) {
        queryModel.productCode = productCode;
        $.ajax({
            url: '${contextPath}/ktProd/getProdSupplier',
            type: 'post',
            data: queryModel,
            success: function (data) {
                console.log(data)
//                layer.closeAll('loading');
                if (data.success == false) {
                    layer.msg("获取出错：" + data.message)
                    layer.closeAll('loading')
                    return
                }
                var dataArray = data;

                app.objcte = dataArray;
            },
            error: function (error) {
                layer.closeAll('loading')
//                layer.closeAll('loading')
            }
        })
    }


    //把数据赋直到jqGrid列中
    $('#supp').click(function () {
        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        var rowData = $(grid_selector).jqGrid('getRowData', id);

        var supplierName_id = "#supplierName_" + rowData.productCode;
        var requireShop_id = "#requireShopId_" + rowData.productCode;

        var supplierName = $("#supplierId").val()

        var supplierId =  $("#supplierId option:selected").attr("name");

//        var rowId = $(grid_selector).jqGrid('getGridParam', 'selrow');
//        var thisid= $(grid_selector).getCol(id,false);//
////        $.each(thisid, function(index, value, array) {
////            $(grid_selector).setCell(value,"shopName","天才");//
////        });

        $(supplierName_id).html(supplierName);
//        $(grid_selector).jqGrid('setCell',rowId,"supplierName",supplierName);  //修改行数据

        $(grid_selector).jqGrid('setCell',id,"supplierId",supplierId);  //修改行数据

        $('#myModal1').modal('hide');
    });

    //数据联动
    var discount = function (productCode,cstPrice) {
        var priceId = "#price_"+productCode;
        var quantityId = "#quantity_"+productCode;
        var quantity = $(quantityId).val();
        quantity = gatQuantity(quantity);
        $(quantityId).val(quantity);
        if(!integerVerify(quantity)){
            $(quantityId).val(0);
            return
        }
        var price = (cstPrice * quantity).toFixed(2);
        $(priceId).html(price)
    }

    var gatQuantity = function (quantity) {
        for( var i=0;i< quantity.length;i++ ){
            var str = quantity.substr(i,1);
            if(str == '0') {
                quantity = quantity.substring(1, quantity.length);
                return gatQuantity(quantity);
            }else {
                return quantity;
            }
        }
    }

    //jqGrid 数据重加载
    var reload = function () {
//        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam', {
            <%--url: "${contextPath}/ktPurchase/getPurchaseItems?id=${id}",--%>
            datatype: 'json',
//                    postData:param,
            page: 1
        }).trigger("reloadGrid"); //重新载入
    }


</script>